//
//  WithdrawAddVC.swift
//  d11
//
//  Created by peale on 2018/11/15.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit
import SwiftyJSON
import Eagleeyes.DevicePrint
class WithdrawAddVC: BXBaseVC ,UITableViewDelegate,UITableViewDataSource{
    let  reuseIdentifierID : String = "WithdrawSelectCell"
    let  reuseIdentifierID2 : String = "WithdrawItemCell"
    let  reuseIdentifierID3 : String = "WithdrawInputMoneyCell"
    let  reuseIdentifierID4 : String = "WithdrawInputCell"
    let  reuseIdentifierID5 : String = "WithdrawInputMoney2Cell"
    let  reuseIdentifierID6 : String = "WithdrawHintCell"
    let  reuseIdentifierID7 : String = "WithdrawBtnCell"
    var balanceButton: UIButton?
    var isNewUser : Bool = false
    var userName :String?  //开户姓名
    var bankAcount :String? //开户账号
    var bankAddress :String? //开户行地区
    var pwdStr:String?  //密码
    var moneyStr:String? //金额
    var dataArray : [[String:Any]]?
    var selectBankIndex :Int = -1
    var selectDict :[String:Any]?
    var process : String? //取款审核中的数目
    var withdraw_min : String? //取款最低金额
    var withdraw_max : String? //取款最高金额
    var  withdrawdaymax : String? //每天取款最高金额
    var withdrawdaylimit: String? //每天取款最高次数
    var playerdailywithdrawtimes :Int = 0
    var playerdailywithdrawamount :Int = 0
    var isShowPwd :Bool = false
    var userBalance : Double = 0
    lazy var tableView:UITableView = {
        let table = UITableView(frame:CGRect(x: 0, y: 0, width: self.view.width, height:kScreenHeight), style:UITableView.Style.plain)
        table.dataSource = self
        table.delegate = self
        //table.layoutMargins = UIEdgeInsets.zero
        table.separatorStyle = .none
        table.backgroundColor  = UIColor.white
        table.showsVerticalScrollIndicator = false
        table.tableFooterView = UIView.init()
        table.separatorStyle = .none
        table.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        table.estimatedRowHeight = 0
        table.estimatedSectionHeaderHeight = 0
        table.estimatedSectionFooterHeight = 0
        if #available(iOS 11.0, *) {
            table.contentInsetAdjustmentBehavior = .never
            
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        return table
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let topLogo = UIImage(named: "icon_nav_left_logo")
        let titleView = UIView()
        let topLogoView = UIImageView(image: topLogo)
        titleView.addSubview(topLogoView)
        topLogoView.contentMode = .scaleToFill
        topLogoView.frame = CGRect(x: -(137/2), y:-(35/2), width: 137, height: 35)
        navigationItem.titleView = titleView
        
        self.balanceButton = self.initRightBarBtn()
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: balanceButton!)
        self.view.backgroundColor = UIColor.white
        self.view.addSubview(self.tableView)
        self.getBankList()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.refreshBalance()
    }
    
    func refreshBalance(){
        if UserHelper.getLoginStatus() {
            print("\(String(describing: GlobalInfo.memberInfoData))")
            if let withBalance = GlobalInfo.memberInfoData!["balance"] as? String {
                if withBalance != ""{
                    let balance: Double = Double(withBalance)!
                    self.userBalance = balance
                    self.balanceButton?.setTitle(String(format: "%.2f", balance), for: .normal)
                    let size = self.balanceButton!.intrinsicContentSize
                    balanceButton!.frame.size = CGSize(width: size.width, height: 33)
                }else{
                    self.balanceButton?.setTitle(String(format: "0.00"), for: .normal)
                }
            }
        }else{
            let button1 = UIBarButtonItem(title: "注册/登录", style: .plain, target: self, action: #selector(self.loginRegisterButtonClick))
            button1.tintColor = HexRGBAlpha(0xFBBC64,1)
            self.navigationItem.setRightBarButtonItems([button1], animated: false)
        }
    }
    
    @objc func loginRegisterButtonClick(){
        setRootLoginVC()
    }
    
    func getBankList(){
        self.showLoadHUD(title: "")
        RequestHelper.post(atPath: "/clientsAPIs/getbank", withData: Dictionary(), withCompletion: { (data) in
             let json = JSON(data)
            print("银行卡列表\(json)")
//            let  logCode=baseInfoArray["m"] as! String
//            if(logCode.isEqual("9999")){
//                DispatchQueue.main.async {
            DispatchQueue.main.async {
                  self.dismissLoadHUD()
               let arrayObject = json.arrayObject as? [[String : Any]]
                if arrayObject == nil{
                    let logCode = json.dictionaryObject?["m"] as? String ?? "0"
                    if logCode == "9999"{
                         UIHelper.displayLoginExpireTip(self)
                    }
                }else{
                    self.dataArray = json.arrayObject as? [[String : Any]] ?? []
                }
                
                  self.tableView.reloadData()
            }
        }) { (error) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                UIHelper.alertSimpleMessage(about: "服务器异常,获取银行卡列表失败。\(getErrorString())", withDescription: "", in: self)
            }
           
        }
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 5
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }else if section == 1{
            return 3
        }else if section == 2{
            if isNewUser == true{ //如果是新用户或者老用户完善过手机号码
                return 1
            }
            return 2
        }else if section == 3{
            return 1
        }else if section == 4{
            return 1
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0{
                return 61
        }else if indexPath.section == 1{
           return 60
        }else if indexPath.section == 2{
            if isNewUser == true{ //如果是新用户或者老用户完善过手机号码
                return 101.5
            }else{
                if indexPath.row == 0{
                    return 101.5
                }else if indexPath.row == 1{
                    return 51
                }
                
            }
        }else if indexPath.section == 3{
            return 200
        }else if indexPath.section == 4{
            return 50
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView.init()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0{//请选择银行卡
            var cell :WithdrawSelectCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID as String) as? WithdrawSelectCell
            if cell == nil {
                cell =  WithdrawSelectCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID as String)
            }
            
            cell?.setData(bankName: selectDict?["bankname"] as? String)
            return cell!
        }else if indexPath.section == 1{
            var cell :WithdrawItemCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID2 as String) as? WithdrawItemCell
            if cell == nil {
                cell =  WithdrawItemCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID2 as String)
            }
            cell?.callChangeBlock({ (text,row) in
                 if row == 0{
                    self.userName = text
                 }else if row == 1{
                    self.bankAcount = text
                 }else{
                    self.bankAddress = text
                }
            });
            var value : String?
            if indexPath.row == 0{
                value = self.userName
            }else if indexPath.row == 1{
                value = self.bankAcount
            }else{
                value = self.bankAddress
            }
            cell?.setData(row: indexPath.row, value: value)
            return cell!
        }else if indexPath.section == 2{
            if isNewUser == true{ //如果是新用户或者老用户完善过手机号码
                //输入金额
                var cell :WithdrawInputMoneyCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID3 as String) as? WithdrawInputMoneyCell
                if cell == nil {
                    cell =  WithdrawInputMoneyCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID3 as String)
                }
                cell?.callChangeBlock({ (money) in
                    self.moneyStr = money
                })
                return cell!
                
            }else{
                if indexPath.row == 0{ //输入金额
                    var cell :WithdrawInputMoney2Cell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID7 as String) as? WithdrawInputMoney2Cell
                    if cell == nil {
                        cell =  WithdrawInputMoney2Cell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID7 as String)
                    }
                    cell?.callChangeBlock({ (money) in
                        self.moneyStr = money
                    })
                    return cell!
                }else if indexPath.row == 1{ //取款密码
                    var cell :WithdrawInputCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID4 as String) as? WithdrawInputCell
                    if cell == nil {
                        cell =  WithdrawInputCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID4 as String)
                    }
                    cell?.callChangeBlock({ (pwd) in
                        self.pwdStr = pwd
                    })
                    cell?.showCallChangeBlock({ (isShow) in
                        self.isShowPwd = isShow
                        self.tableView.reloadData()
                    })
                    cell?.setData(inputText: self.pwdStr, row: indexPath.row,isShow:self.isShowPwd)
                    return cell!
                }
            }
        }else if indexPath.section == 3{ //提示
            var cell :WithdrawHintCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID5 as String) as? WithdrawHintCell
            if cell == nil {
                cell =  WithdrawHintCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID5 as String)
            }
            cell?.setData(isRed: true)
            return cell!
        }else if indexPath.section == 4{ //提交按钮
            var cell :WithdrawBtnCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID6 as String) as? WithdrawBtnCell
            if cell == nil {
                cell =  WithdrawBtnCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID6 as String)
            }
            cell?.callClickBlock({
                DispatchQueue.main.async {
                    self.submitAddWithdraw()
                }
                
            })
            return cell!
        }
        
         return UITableViewCell.init()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0{
            if indexPath.row == 0{
                self.showBankInfoPopView()
            }
        }
    }
    
    //提交数据
    func submitAddWithdraw() -> Void {
        if playerdailywithdrawtimes >= (Int(self.withdrawdaylimit ?? "0") ?? 0){
           UIHelper.alertSimpleMessage(about: "每天取款上限为\(self.withdrawdaylimit ?? "0")次,您可以在明天继续取款！", withDescription: "", in: self)
            return
        }
//        if playerdailywithdrawamount >= (Int(self.withdrawdaymax ?? "0") ?? 0){
//            UIHelper.alertSimpleMessage(about: "每天最多可以取款金额：\(self.withdrawdaymax ?? "0")元", withDescription: "", in: self)
//            return
//        }
        
        if self.selectBankIndex == -1 {
             UIHelper.alertSimpleMessage(about: "请选择银行种类!", withDescription: "", in: self)
            return
        }
        
        if self.userName == nil || self.userName == ""{
            UIHelper.alertSimpleMessage(about: "请输入开户姓名!", withDescription: "", in: self)
            return
        }
        
        if self.bankAcount == nil || self.bankAcount == ""{
            UIHelper.alertSimpleMessage(about: "请输入开户账号!", withDescription: "", in: self)
            return
        }
        if (self.bankAcount?.count)! < 6{
            UIHelper.alertSimpleMessage(about: "开户账号不能少于6位数!", withDescription: "", in: self)
            return
        }
        if self.bankAddress == nil || self.bankAddress == ""{
            UIHelper.alertSimpleMessage(about: "请输入开户行地址!", withDescription: "", in: self)
            return
        }
        let money : Double = Double(self.moneyStr ?? "-1") ?? -1

        if self.moneyStr == nil || self.moneyStr == ""{
            UIHelper.alertSimpleMessage(about: "请输入取款金额!", withDescription: "", in: self)
            return
        }
        
        if money > self.userBalance{
            UIHelper.alertSimpleMessage(about: "余额不足", withDescription: "", in: self)
            return
        }
        
        
        if self.isNewUser == false{
            if self.pwdStr == nil || self.pwdStr == ""{
                UIHelper.alertSimpleMessage(about: "请输入取款密码!", withDescription: "", in: self)
                return
            }
            if (self.pwdStr?.count)! < 6{
                UIHelper.alertSimpleMessage(about: "取款密码错误!", withDescription: "", in: self)
                return
            }
        }
        
        if self.moneyStr == nil || self.moneyStr == "0" || self.moneyStr == ""{
            UIHelper.alertSimpleMessage(about: "请输入取款金额!", withDescription: "", in: self)
            return
        }
      
        let min : Double  = Double(self.withdraw_min ?? "0") ?? 0
        let max : Double  = Double(self.withdraw_max ?? "0") ?? 0
        if money < min{
            UIHelper.alertSimpleMessage(about: "取款金额不能小于\(self.withdraw_min ?? "未知错误")!", withDescription: "", in: self)
            return
        }
        
        if  money > max{
            UIHelper.alertSimpleMessage(about: "取款金额不能大于\(self.withdraw_max ?? "未知错误")!", withDescription: "", in: self)
            return
        }
        
        if self.isNewUser == false{
            if self.pwdStr == nil || self.pwdStr == ""{
                UIHelper.alertSimpleMessage(about: "请输入取款密码!", withDescription: "", in: self)
                return
            }
            
            if (self.pwdStr?.count)! < 6{
                UIHelper.alertSimpleMessage(about: "取款密码不能少于6位数!", withDescription: "", in: self)
                return
            }
        }
        
        var params:[String:Any] = [
            "amount":self.moneyStr ?? "0", //金额
            "bankname": selectDict?["bankname"] as? String ?? "", //银行名称
            "bankcode": selectDict?["bankcode"] as? String ?? "", //银行代码
            "banknode": self.bankAddress ?? "", //开户行地区
            "account":self.userName ?? "",
            "card": self.bankAcount ?? "",
            "wdbank":"",
            "note": "",
            "address": "",
            "addra":"",
            "addrb":"",
            "wdpassword":""
        ]
        if self.isNewUser == false{
            params["wdpassword"]  = self.pwdStr
        }
        self.showLoadHUD(title: "提交中...")
        NetWorkRequest(API.submitWithdrawFund(url: "85077d9", params:params), completion: { (responseData,statusCode,strData) -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                let dict  = responseData.dictionaryObject
                let data = dict?["data"] as? [String:Any]
                let res  = data?["response"] as? [String:Any]
                let code =  res?["c"] as? Int ?? -1
                if code == 0{
                    self.requestEagleeyes(dno:"")
                    let vc =  WithdrawCheckingVC()
                    let totalBankList = GlobalInfo.bankList
                    if totalBankList != nil {
                        for  (_ ,dict) in (totalBankList?.enumerated())!{
                            if self.selectDict?["bankcss"] as? String ?? "" == dict["logo"] as? String ?? ""{
                                vc.bankIconStr =  dict["image"] as? String ?? ""
                                break
                            }
                        }
                    }
                    vc.bankname = self.selectDict?["bankname"] as? String
                    vc.cardnum = self.bankAcount
                    self.navigationController?.pushViewController(vc, animated: true)
                }else if code == 999 || code == 1150 {
                    UIHelper.displayLoginExpireTip(self)
                }else{
                    UIHelper.alertSimpleMessage(about: "\(CodeMessageHelper.get(String(code)))", withDescription: "", in: self)
                }
             
            }
        }, failed: { (faildInfo,reCode,msg) -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                if reCode == "21002"{
                    UIHelper.displayLoginExpireTip(self)
                }else{
                    UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                }
            }
        }) { () -> (Void) in
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                UIHelper.alertSimpleMessage(about: "网络请求异常!", withDescription: "", in: self)
            }
        }
    }
    
    //弹出银行选择
    func showBankInfoPopView(){
        if self.dataArray != nil && (self.dataArray?.count)! > 0 {
            var arrayString = [String]()
            for dict in self.dataArray! {
                let string =  dict["bankname"] as? String ?? "未知"
                arrayString.append(string)
            }
            UsefulPickerView.showSingleColPicker("", data: arrayString, defaultSelectedIndex: 0) { (selecedIndex, title) in
                DispatchQueue.main.async {
                    self.selectBankIndex = selecedIndex
                    self.selectDict = self.dataArray?[self.selectBankIndex]
                    self.tableView.reloadData()
                }
            }
        }else{
             UIHelper.alertSimpleMessage(about: "暂无银行列表数据!", withDescription: "", in: self)
        }
       
    }
    
    //调用鹰眼接口
    func requestEagleeyes(dno:String){
//        RequestHelper.get(atPath:"/home/getGeo", withCompletion: { (data) in
//            var dataArray = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
//            print("获取IP\(dataArray)")
//            if let ip = dataArray?["ip"] as? String {
//                DispatchQueue.main.async {
                    let blackbox :String = DevicePrint.getBlackBox() ?? ""
                    NetWorkRequest(API.requsetEagleeyes2(url: "94a0356", blackBox: blackbox, type: "withdrawal", dno: dno,ipaddress:""), completion: { (responseData,statusCode,strData) -> (Void) in
                        print("取款后鹰眼返回:",responseData,statusCode,strData)
                    }, failed: { (faildInfo,reCode,msg) -> (Void) in
                        print("取款后鹰眼返回:",faildInfo,reCode,msg)
                    }) { () -> (Void) in
                        print("取款后鹰眼返回错误")
                    }
                }
//            }
//        }, withError: { error in
//        })
//    }//withdrawal deposit
}
